﻿using System;
using System.Text.RegularExpressions;
using RuTracker.Interface;
using RuTracker.Interface.Login;
using RuTrackerLib.ServiceAttibutes;

namespace RuTrackerLib.Tracker
{
    [PerCallService]
    public class RuTrackerResponseLexer : IResponseLexer
    {
        public LoginResults GetResults(string html)
        {
            if (string.IsNullOrEmpty(html))
                throw new ArgumentNullException(html);

            if (!IsUserLoggedIn(html))
            {
                string captureCode, captcahUrl, captureSid;
                if (IsCaptureRequired(html, out captcahUrl, out captureCode, out captureSid))
                    return LoginResults.CreateCatchaRequired(html, captcahUrl, captureCode, captureSid);

                return LoginResults.CreateInvalidUserNameOrPassowrd(html);
            }

            return LoginResults.CreateSucceeded(html);
        }

        private bool IsCaptureRequired(string html
            , out string capchaUrl
            , out string captureCode
            , out string captureSid)
        {
            capchaUrl = GetCaptchaUrl(html);
            captureCode = GetCaptchaCode(html);
            captureSid = GetCaptchaSid(html);

            return !(string.IsNullOrWhiteSpace(captureCode) && string.IsNullOrWhiteSpace(capchaUrl) && string.IsNullOrWhiteSpace(captureSid));
        }

        public bool IsUserLoggedIn(string html)
        {
            return html.Contains(@"Вы зашли как:");
        }

        public bool ContainsTorrent(string html)
        {
            return html.Contains("Скачать .torrent");
        }

        private string GetCaptchaSid(string html)
        {
            Regex regex = new Regex("name=\"cap_sid\" value=\"(?<sid>.*?)\"");
            Match match = regex.Match(html);
            return match.Groups["sid"].Success ? match.Groups["sid"].Value : string.Empty;

        }

        private string GetCaptchaCode(string html)
        {
            Regex regex = new Regex("cap_code_(?<id>.*?)\"");
            Match match = regex.Match(html);
            return match.Groups["id"].Success
                ? string.Format("cap_code_{0}", match.Groups["id"].Value)
                : string.Empty;

        }

        private string GetCaptchaUrl(string html)
        {
            Regex regex = new Regex("\"http://static.rutracker.org/captcha/.*?\"");
            Match match = regex.Match(html);
            return match.Success ? match.Value.Replace("\"", string.Empty) : string.Empty;
        }
    }
}
